/*
Copyright (C) 2022-2024 Inspur Corp.

SPDX-License-Identifier: Apache-2.0
*/
package auth

import (
	"github.com/emicklei/go-restful"
	chttp "icep/common/http"
	"icep/common/jwt"
	"icep/plugins/sessionmgr"
	"net/http"
)

func AuthFilter(req *restful.Request, resp *restful.Response, chain *restful.FilterChain) {
	ret, payload, _ := jwt.ValidateToken(req.Request)
	if ret && sessionmgr.Get().Check(payload.UserId, req.Request) {
		req.SetAttribute("CUR_USER", payload)
		req.SetAttribute("CUR_USER_ID", payload.UserId)
		req.SetAttribute("CUR_USER_TYPE", payload.UserType)
		req.SetAttribute("CUR_USER_TENANT_ID", payload.TenantId)
		req.SetAttribute("CUR_USER_MAIL", payload.Mail)
		req.SetAttribute("CUR_USER_PHONE", payload.Phone)

		chain.ProcessFilter(req, resp)
	} else {
		// validate failed
		chttp.FailedWithStatus(resp, http.StatusUnauthorized, "认证失败")
		return
	}
}

func GetCurrentUserId(req *restful.Request) string {
	userId := req.Attribute("CUR_USER_ID")
	return userId.(string)
}

func GetCurrentUserType(req *restful.Request) string {
	userId := req.Attribute("CUR_USER_TYPE")
	return userId.(string)
}

func GetCurrentTenantId(req *restful.Request) string {
	userId := req.Attribute("CUR_USER_TENANT_ID")
	return userId.(string)
}

func GetCurrentMail(req *restful.Request) string {
	userId := req.Attribute("CUR_USER_MAIL")
	return userId.(string)
}

func GetCurrentPhone(req *restful.Request) string {
	userId := req.Attribute("CUR_USER_PHONE")
	return userId.(string)
}
